import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import './style.css'
import App from './App.vue'
import { useUserStore } from './store/user'
import '@vant/touch-emulator';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

// 导入 Vant 组件
import { Button, Cell, CellGroup, Icon, SwipeCell, List, Tabbar, TabbarItem, ImagePreview, Loading, Overlay, Popup, Calendar, Notify, Search, Swipe, SwipeItem, DatePicker, Form, Field, Checkbox, CheckboxGroup, Tag, Switch, NavBar, Picker, ActionSheet, Dialog, Badge } from 'vant'
import 'vant/lib/index.css'

const app = createApp(App)
const pinia = createPinia()

// 使用 Pinia 持久化插件
pinia.use(piniaPluginPersistedstate)

// 使用 Pinia
app.use(pinia)

// 使用 Vue Router
app.use(router)

// 注册 Vant 组件
app.use(Button)
app.use(Cell)
app.use(CellGroup)
app.use(Icon)
app.use(Loading)
app.use(Popup)
app.use(Calendar)
app.use(Search)
app.use(Swipe)
app.use(SwipeItem)
app.use(Form)
app.use(Field)
app.use(Checkbox)
app.use(CheckboxGroup)
app.use(Tag)
app.use(Switch)
app.use(NavBar)
app.use(Picker)
app.use(Notify)
app.use(ActionSheet)
app.use(Dialog)
app.use(Overlay)
app.use(Badge)
app.use(DatePicker)
app.use(ImagePreview)
app.use(SwipeCell)
app.use(List)
app.use(Tabbar);
app.use(TabbarItem);

// 在应用挂载前恢复用户登录状态
// 必须在app.mount之前获取store实例，因为mount后会触发路由守卫
const userStore = useUserStore()
const token = localStorage.getItem('token')
if (token) {
  // 如果userInfo为空，静默获取用户信息，不阻塞应用初始化
  if (!userStore.userInfo) {
    userStore.fetchUserInfo().catch(err => {
      console.error('恢复用户信息失败:', err)
      // 如果获取用户信息失败，清空token，确保用户状态一致性
      userStore.logout()
    })
  }
}

app.mount('#app')
